﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace JiraRest
{
    public static class JiraUtils
    {
        private const string c_EscapeString = "\\";

        /// <remarks>
        /// <see cref="c_EscapeString"/> must be first!
        /// </remarks>
        private static readonly string[] s_ReservedStrings = new[] { c_EscapeString, "\"", "'" };
        
        internal static string JqlEscape(IEnumerable<char> unescaped)
        {
            string cleaned = Clean(unescaped, false);
            return s_ReservedStrings.Aggregate(cleaned, (acc, reservedString) => acc.Replace(reservedString, c_EscapeString + reservedString));
        }

        public static string Clean(IEnumerable<char> dirty, bool isJson)
        {
            StringBuilder sb = new StringBuilder();
            dirty.Where(IsClean).Select(x => Convert(x, isJson)).Aggregate(sb, (x, y) => x.Append(y));
            return sb.ToString().Trim();
        }

        private static bool IsClean(char x)
        {
            return !Char.IsControl(x) || Char.IsWhiteSpace(x);
        }

        private static string Convert(char x, bool isJson)
        {
            switch (x)
            {
                case '“':
                case '”':
                    // if these characters are inserted into JIRA, they get converted to an unescaped ".
                    // This breaks things as " is a special character in JSON
                    // so we need to escape them ourselves here.
                    return isJson ? "\\\"" : "\"";
                default:
                    return x.ToString();
            }
        }
    }
}
